package com.zhuchaooasystem.ui.home.fragment.oa.sign;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.SignTrailEntity;
import com.zhuchaooasystem.entity.UserInfo;
import com.zhuchaooasystem.presenter.home.fragment.oa.sign.SignTrailContract;
import com.zhuchaooasystem.presenter.home.fragment.oa.sign.SignTrailPresenter;
import com.zhuchaooasystem.utils.CalendarUtils;
import com.zhuchaooasystem.utils.ScreenUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class SignTrailActivity extends BaseActivity<SignTrailPresenter> implements SignTrailContract.View {

    @BindView(R.id.act_sign_trail_relative_rootview)
    RelativeLayout relative_parent;
    @BindView(R.id.act_sign_trail_txt_calendar)
    TextView tv_calendar;
    //----
    @BindView(R.id.act_sign_trail_mapview)
    MapView mapview;
    @BindView(R.id.act_sign_trail_txt_desc)
    TextView tv_desc;

    //----
    private String cur_date;
    private String username;
    //----地图相关
    private BaiduMap baiduMap;
    // 初始化全局 bitmap 信息，不用时及时 recycle
    private BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
            .fromResource(R.drawable.ic_location);
    private TextView tv_marker;
    private BitmapDescriptor bitmapDescriptorText;
    private MarkerOptions markerOptions;


    @Override
    protected int getLayout() {
        return R.layout.activity_sign_trail;
    }

    @Override
    protected SignTrailPresenter getPresenter() {
        return new SignTrailPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        cur_date = CalendarUtils.getNow("yyyy/MM/dd");
        username = UserInfo.getInstance().getUserName();
        baiduMap = mapview.getMap();
    }

    @Override
    protected void initView() {
        tv_calendar.setText(cur_date);
        //----
        if (null == baiduMap) {
            ToastUtil.showShort(mContext, "地图信息获取失败");
            finish();
        } else {
            baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(16).build()));
            tv_marker = new TextView(mContext);
            tv_marker.setLayoutParams(new ViewGroup.LayoutParams(ScreenUtils.dip2px(mContext, 30), ScreenUtils.dip2px(mContext, 30)));
            tv_marker.setBackgroundResource(R.drawable.ic_location_fill);
            tv_marker.setTextColor(Color.WHITE);
            tv_marker.setTextSize(12);
            tv_marker.setGravity(Gravity.CENTER);
        }
    }

    @Override
    protected void initDataAndLoadData() {
        //权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE}, Key.LOCATION);
        } else {
            //----
            mPresenter.drawUserLineInfo();
        }
    }

    @OnClick({R.id.act_sign_trail_iv_back, R.id.act_sign_trail_txt_calendar})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.act_sign_trail_iv_back:
                finish();
                break;
            //选择日期
            case R.id.act_sign_trail_txt_calendar:
                new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                        cur_date = year + "/" + (monthOfYear + 1) + "/" + dayOfMonth;
                        tv_calendar.setText(cur_date);
                        mPresenter.drawUserLineInfo();
                    }
                }, Integer.parseInt(cur_date.split("/")[0]), (Integer.parseInt(cur_date.split("/")[1]) - 1), Integer.parseInt(cur_date.split("/")[2])).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onPause();
        }
    }


    @Override
    public String getCurDate() {
        return cur_date;
    }

    @Override
    public void refreshView(List<SignTrailEntity.ResultBean.SuccessfulBean> signTrailList) {
        clearOverlay();
        if (null != signTrailList && signTrailList.size() > 0) {
            initOverlay(signTrailList);
        } else {
            tv_desc.setText(username + "  今日已签到0次");
        }
    }

    /**
     * 清除所有Overlay
     */
    private void clearOverlay() {
        baiduMap.clear();
    }

    private void initOverlay(List<SignTrailEntity.ResultBean.SuccessfulBean> list_sign_trails) {
        if (null != list_sign_trails && list_sign_trails.size() > 0) {
            List<String> list_lngs = new ArrayList<>();
            boolean hasLocation = false;
            int signCount = 0;
            for (int i = 0; i < list_sign_trails.size(); i++) {
                SignTrailEntity.ResultBean.SuccessfulBean trail = list_sign_trails.get(i);
                if (trail.getLatiude() != 0 && trail.getLongitude() != 0) {
                    signCount += 1;
                    if (hasLocation == false) {
                        baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(trail.getLatiude(), trail.getLongitude())));
                    }
                    hasLocation = true;
                    if (list_lngs.contains(trail.getLatiude() + ";" + trail.getLongitude())) {
                        int count = 1;
                        for (String lng : list_lngs) {
                            if (lng.equals(trail.getLatiude() + ";" + trail.getLongitude())) {
                                count++;
                            }
                        }
                        tv_marker.setText(count + "");
                        bitmapDescriptorText = BitmapDescriptorFactory.fromView(tv_marker);
                        list_lngs.add(trail.getLatiude() + ";" + trail.getLongitude());
                        markerOptions = new MarkerOptions().position(new LatLng(trail.getLatiude(), trail.getLongitude())).icon(bitmapDescriptorText)
                                .zIndex(0).period(3).draggable(false);
                    } else {
                        list_lngs.add(trail.getLatiude() + ";" + trail.getLongitude());
                        markerOptions = new MarkerOptions().position(new LatLng(trail.getLatiude(), trail.getLongitude())).icon(bitmapDescriptor)
                                .zIndex(0).period(3).draggable(false);
                    }
                    // 生长动画
                    markerOptions.animateType(MarkerOptions.MarkerAnimateType.grow);
                    //----
                    baiduMap.addOverlay(markerOptions);
                }
            }
            tv_desc.setText(username + "  今日已签到" + signCount + "次");
        }
    }

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.LOCATION:
                mPresenter.drawUserLineInfo();
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }


}
